package com.steven.learnjava.controller;

import com.steven.learnjava.entity.User;
import com.steven.learnjava.mapper.UserMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.ResponseEntity;

import java.util.List;

@RestController
@RequestMapping("/users")
@Tag(name = "用户管理", description = "用户相关接口")
public class UserController {

    private final UserMapper userMapper;

    public UserController(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @GetMapping
    @Operation(summary = "获取所有用户")
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public ResponseEntity<String> register(@RequestBody User user) {
        // if (user.getUsername() == null || user.getPassword() == null || user.getEmail() == null) {
        //     return ResponseEntity.badRequest().body("用户名、密码和邮箱不能为空");
        // }
        userMapper.insert(user);
        return ResponseEntity.ok("注册成功");
    }

    @PutMapping("/{id}/password")
    @Operation(summary = "修改密码")
    public ResponseEntity<String> updatePassword(
            @PathVariable Integer id,
            @RequestBody String newPassword) {
        if (newPassword == null || newPassword.trim().isEmpty()) {
            return ResponseEntity.badRequest().body("新密码不能为空");
        }
        int result = userMapper.updatePassword(id, newPassword);
        if (result > 0) {
            return ResponseEntity.ok("密码修改成功");
        }
        return ResponseEntity.badRequest().body("用户不存在");
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户")
    public ResponseEntity<String> deleteUser(@PathVariable Integer id) {
        int result = userMapper.deleteById(id);
        if (result > 0) {
            return ResponseEntity.ok("用户删除成功");
        }
        return ResponseEntity.badRequest().body("用户不存在");
    }
}
